<template>
    <div class="form-group fast-select-area" style="align-items: baseline;">
        <label :for="id" :class="labelClass" :style="finalLabelStype"><span v-if="required" class="required ">*</span>{{title}}：</label>
        <div :class="rightClass" :style="rightStyle">
            <nly-col sm="12" class="select-col">
                <a-select class="fast-select" style="margin-bottom:8px;width:500px;" v-model="fastSelectValue" @change="selectChange" option-label-prop="label">
                    <a-select-option :label="item.title" v-for="(item, index) in selectOptiontData" :key="item.key + index" :value="item.key">
                        <slot name="option" :item="item">{{ item.title }} </slot>
                    </a-select-option>
                </a-select>
                <div class="mb-1 select-data-edit"><i class="fa fa fa-list-alt" style=" cursor: pointer;" @click="showModal"></i></div>

            </nly-col>

            <form-pop :content="error" />
            <a-textarea @change="onChange" :title="value" :value="value" class="form-control" style="width:100%;" :rows="5" />
        </div>
        <a-modal title="快速短语编辑" :visible="ModalVisible" @cancel="hideModal">
            <template slot="footer">
                <a-button key="back" @click="hideModal">
                    关闭
                </a-button>
            </template>
            <div style="min-height:250px;">

                <a-button type="primary" class="crm-btn" @click="AddItem">新增</a-button>
                <a-button type="primary" class="crm-btn" @click="SaveAllEditItems">保存全部</a-button>
                <a-table class="my-fast-table" :columns="columns" :data-source="data" bordered :pagination="false" style="margin-top:10px;">
                    <div title="上下拖动排序" slot="sort" slot-scope="text" style="cursor: move;">{{text}}</div>
                    <a-input slot="contentVal" slot-scope="text, record" v-model="record.contentVal" @change="ItemEdit(record)"></a-input>
                    <!-- 操作 -->
                    <template slot="operate" slot-scope="text, record, index">
                        <div class="row justify-content-md-center">
                            <span class="col"></span>
                            <span class="col-sm-auto col-md-auto col-lg-auto col-xl-auto">
                                <a href="javascript:;" title="删除" class="mr-1 col-1" @click="Delete(record,index)"><i class="fa fa-trash-alt" style="color: #dd5a43;"></i></a>
                            </span>
                            <span class="col"></span>
                        </div>
                    </template>
                </a-table>
            </div>
        </a-modal>
    </div>
</template>

<script>

import formAttr from "@/mixins/form/form-attr";
import { List, BatchSave, BatchDelete } from "@/api/crm/phrase";
import { DisAbleFirfoxDrag } from "@/utils/browser";
import Sortable from 'sortablejs';

const defaultLabelStype =
    "font-weight: normal;justify-content: flex-end;padding-left: 5px;text-align: right;width:110px;";
export default {
    name: "FormFastArea",
    mixins: [formAttr],
    data () {
        const columns = [
            {
                title: "排序",
                dataIndex: "sort",
                key: "sort",
                width: 80,
                scopedSlots: { customRender: "sort" }
            },
            {
                title: "短语内容",
                dataIndex: "contentVal",
                key: "contentVal",
                width: 200,
                scopedSlots: { customRender: "contentVal" }
            },
            {
                title: "操作",
                dataIndex: "operate",
                key: "operate",
                width: 80,
                scopedSlots: { customRender: "operate" }
            }
        ];
        return {
            fastSelectValue: "",
            ModalVisible: false,
            columns,
            data: [],
            selectedRowKeys: []     //table选中的项

        }
    },
    created () {
        DisAbleFirfoxDrag();
        this.List();
    },
    computed: {
        finalLabelStype: function () {
          let { value } = this;
          if(!value)this.fastSelectValue = "";
          return this.labelStyle || defaultLabelStype;
        },
        selectOptiontData: function () {
            const { data } = this;
            let options = [];
            data.forEach(item => {
                options.push({
                    key: item.contentVal,
                    title: item.contentVal,
                })
            });
            return options;
        }
    },
    methods: {
        onChange (event) {
            console.log("Area_change", event.target.value)
            this.$emit('input', event.target.value);
        },
        selectChange (val) {
            let value = this.value + val + "，";
            this.$emit('input', value);
        },
        onTableSelectChange (selectedRowKeys) {
            Object.assign(this, {
                selectedRowKeys
            })
        },
        AddItem () {
            const { data } = this;
            data.push({
                contentVal: '',
                sort: data.length + 1
            })
        },
        // 获取列表
        List () {
            const { ModalVisible } = this;
            List()
                .then(response => {

                    if (response.code === 200) {
                        const { data } = response;
                        Object.assign(this, {
                            data
                        });
                        if (ModalVisible && data && data.length > 0) {
                            this.drag();
                        }
                    }
                })
                .catch(error => { });
        },
        //批量保存
        SaveAllEditItems () {
            //1.筛选 isEdit = true 的记录
            let editList = this.data.filter(f => f.isEdit);
            if (!editList || editList.length == 0) {
                this.$info({
                    title: "提示",
                    content: '你没有做任何修改',
                });
                return false;
            }
            BatchSave(editList)
                .then(response => {
                    if (response.code === 200) {
                        this.$message.success("保存成功");
                        //刷新 列表
                        this.List();
                    }
                })

        },
        //删除
        Delete (row, index) {
            let _this = this;
            this.$confirm({
                title: '确认',
                content: <span>您确定要{<span style='color:red;'>删除</span>}该记录吗？</span>,
                onOk () {
                    if (!row.id) {
                        _this.data.splice(index, 1);
                        return false;
                    }
                    BatchDelete({ ids: row.id })
                        .then(response => {
                            if (response.code === 200) {
                                _this.$message.success("删除成功");
                                //删除 this.data 对象
                                _this.data.splice(index, 1);
                            }
                        })
                        .catch(err => {
                            const { data } = err.response;
                            _this.$message.error(data.message);
                        });
                },
                onCancel () { },
            });
        },
        //显示modal
        showModal () {
            const { data } = this;
            this.ModalVisible = true;
            if (data && data.length > 0) {
                this.$nextTick(function () {
                    this.drag();
                });
            }
        },
        hideModal () {
            this.ModalVisible = false;
        },
        //该对象是否更改过
        ItemEdit (row) {
            console.log("ItemEdit_row", row)
            row.isEdit = true;
        },
        // 拖动
        drag () {
            // 首先获取需要拖拽的dom节点
            const el1 = document.querySelectorAll('.my-fast-table .ant-table-tbody')[0];
            console.log("el1___", el1)
            if (!el1) return false;
            this.isDrag = true;
            Sortable.create(el1, {
                disabled: false, // 是否开启拖拽
                ghostClass: 'sortable-ghost', //拖拽样式
                animation: 150, // 拖拽延时，效果更好看
                group: { // 是否开启跨表拖拽
                    pull: false,
                    put: false
                },
                onEnd: (e) => { // 这里主要进行数据的处理，拖拽实际并不会改变绑定数据的顺序，这里需要自己做数据的顺序更改
                    let arr = this.data; // 获取表数据

                    let removeItem = arr.splice(e.oldIndex, 1)[0];

                    arr.splice(e.newIndex, 0, removeItem); // 数据处理
                    //提前 赋值一个带值的数组（BUG 修复）
                    this.data = [{}];
                    this.$nextTick(function () {
                        this.data = [...arr];
                        this.data.map((item, index) => {
                            item.sort = index + 1;
                            item.isEdit = true;
                        });
                    });
                }
            });
        }

    }
}
</script>
<style lang="less">
    .fast-select-area {
        .select-col {
            padding: 0px !important;
            flex-grow: 1;
            display: flex;
            .fast-select {
                flex-grow: 1;
                display: flex;
                flex-direction: column;
            }
            .select-data-edit {
                width: 80px;
                font-size: 2rem;
                text-align: center;
                line-height: 32px;
                color: #40a9ff;
            }
        }
    }
</style>

